package com.qf.pck.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.pck.entity.Package;
import com.qf.pck.entity.PackageOrder;
import com.qf.pck.mapper.PackageMapper;
import com.qf.pck.mapper.PackageOrderMapper;
import com.qf.pck.service.PackageOrderService;
import com.qf.tenant.entity.Tenant;
import com.qf.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhu
 * @since 2023-10-27
 */
@Service
public class PackageOrderServiceImpl extends ServiceImpl<PackageOrderMapper, PackageOrder> implements PackageOrderService {

    @Autowired(required = false)
    private PackageMapper packageMapper;


    @Override
    @Transactional
    public R<String> order(String pckId) {
        //1：查询套餐信息
        Package pck = packageMapper.selectById(pckId);
        if (pck == null) {
            return R.fail("套餐不存在");
        }


        Tenant tenant = (Tenant) SecurityContextHolder.getContext().getAuthentication().getPrincipal();


        //2：判断用户是否未支付的订单
        QueryWrapper<PackageOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PackageOrder::getTenantId,tenant.getId())
                .eq(PackageOrder::getPackageId,pckId)
                .eq(PackageOrder::getPayStatus,0);
        PackageOrder orderNoPay = this.baseMapper.selectOne(queryWrapper);
        if (orderNoPay != null) {
            return R.ok(orderNoPay.getId(),"您有未支付订单,请先支付");
        }

        //3：生成订单
        PackageOrder order = new PackageOrder();
        order.setPackageId(pck.getId());
        order.setCreateTime(new Date());
        order.setMoney(pck.getPrice());
        String orderId = IdWorker.getIdStr();
        order.setId(orderId);
        order.setPayStatus(0);
        order.setTenantId(tenant.getId());
        order.setPayno(orderId);
        this.baseMapper.insert(order);

        return R.ok(orderId,"下单成功");
    }
}
